package com.swing.gui.component;

import com.swing.gui.component.popups.LockMenu;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * @author Yuang, Gongming
 * @date 2022-01-20 14:30
 */
public class MiniPopup extends JDialog {

    private static MiniPopup popup;
    public static JPopupMenu jPopupMenu = LockMenu.init();

    private MiniPopup() {
    }

    public static MiniPopup init() {
        if (popup == null) {
            synchronized (MiniPopup.class) {
                if (popup == null) {
                    popup = new MiniPopup();
                    try {
                        template();
                        listener();

                    } catch (Exception e) {
                        throw new RuntimeException(MiniPopup.class.getSimpleName() + " - initialization failed");
                    }
                }
            }
        }
        popup.setLocation((int) MouseInfo.getPointerInfo().getLocation().getX(), (int) (MouseInfo.getPointerInfo().getLocation().getY() - MiniPopup.jPopupMenu.getPreferredSize().getHeight()));
        popup.setVisible(true);
        jPopupMenu.show(popup, 0, 0);
        return popup;
    }

    private static void template() {
        popup.setUndecorated(true);
        popup.setBackground(new Color(0, 0, 0, 0));
        popup.setLayout(null);  //  必要的空布局
        popup.setLocation((int) MouseInfo.getPointerInfo().getLocation().getX(), (int) (MouseInfo.getPointerInfo().getLocation().getY() - MiniPopup.jPopupMenu.getPreferredSize().getHeight()));
        popup.setAlwaysOnTop(true);
    }

    private static void listener() {
        popup.addWindowFocusListener(new WindowAdapter() {
            @Override
            public void windowLostFocus(WindowEvent e) {
                System.out.println("弹出框 - 失去焦点" + System.currentTimeMillis());
                popup.setVisible(false);
            }
        });
    }

}
